#import "LyricsFetcherAppDelegate.h"

@implementation LyricsFetcherAppDelegate

@synthesize lyricsWindow;
@synthesize lyricsText;
@synthesize menu;
@synthesize statusItem;
@synthesize controller;
@synthesize provider;
@synthesize updateLyricsIfEmptyItem;
@synthesize toggleLyricsWindowItem;

- (IBAction) updateCurrentTrackLyrics:(id)sender {
	[self.controller updateCurrentTrackLyrics:[self.lyricsText string]];
}

- (IBAction) toggleLyricsWindow:(NSMenuItem *)item {
	if ([self.lyricsWindow isVisible]) {
		[self.lyricsWindow close];
	}
	else {
		[self.lyricsWindow makeKeyAndOrderFront:item];
		[item setTitle:@"Hide Lyrics"];
	}
}

- (IBAction) toggleUpdateLyricsIfEmptyOption:(NSMenuItem *)item {
	if ([item state] == NSOnState)
		[item setState:NSOffState];
	else
		[item setState:NSOnState];
}

- (IBAction) displayCurrentTrackInfo:(id)sender {
	TrackInfo *track = [self.controller getCurrentTrack];
	if (track != nil) {
		[self.lyricsWindow setTitle:
			[NSString stringWithFormat:@"%@: %@", track.artist, track.name]
		];		
		
		[self.provider beginFetchLyricsForSong:track];
		
		[track release];
	}
}

- (IBAction) lyricsWindowClosing:(id)sender {
	[self.toggleLyricsWindowItem setTitle:@"Show Lyrics"];
}

- (void) updateMenuOnWindowClose:(NSNotification *)notification {
	[self.toggleLyricsWindowItem setTitle:@"Show Lyrics"];
}

- (void) createStatusBarItem {
	self.statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
	if (self.statusItem != nil) {
		[self.statusItem setMenu:self.menu];
		[self.statusItem setImage:[NSImage imageNamed:@"lyricsFetcherStatus.png"]];
		[self.statusItem setHighlightMode:YES];
	}
}

- (void) subscribeToNotifications {
	[[NSNotificationCenter defaultCenter] 
		addObserver:self 
		selector:@selector(updateMenuOnWindowClose:) 
		name: NSWindowWillCloseNotification
		object:self.lyricsWindow
	 ];
	
	[[NSNotificationCenter defaultCenter] 
		addObserver:self 
		selector:@selector(updateLyrics:) 
		name:@"lyricsFetched" 
		object:nil
	];
	
	[[NSDistributedNotificationCenter defaultCenter] 
		addObserver:self 
		selector:@selector(receivediTunesNotification:) 
		name:@"com.apple.iTunes.playerInfo"
		object:nil
	];
}

- (void) unsubscribeFromNotifications {
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
}

- (void) applicationDidFinishLaunching:(NSNotification *)aNotification {
	self.controller = [[iTunesController alloc] init];
	self.provider = [[ChartLyricsLyricsProvider alloc] init];
	
	[self subscribeToNotifications];	
	[self createStatusBarItem];
}

- (void) receivediTunesNotification:(NSNotification *)notification {
	NSDictionary *userInfo = [notification userInfo];
	NSString *state = [userInfo objectForKey:@"Player State"];
	if (![state isEqualToString:@"Playing"])
		return;
	
	TrackInfo *track = [[TrackInfo alloc] 
	    initWithName: [userInfo objectForKey:@"Name"]
		artist:		  [userInfo objectForKey:@"Artist"]
		id:			  [[userInfo objectForKey:@"Library PersistentID"] intValue]
		lyrics:		  [userInfo objectForKey:@"Lyrics"]
	];
	
	[self.lyricsWindow setTitle:
		[NSString stringWithFormat:@"%@: %@", track.artist, track.name]
	];
	
	if ([track.lyrics length] == 0) {
		[self.provider beginFetchLyricsForSong:track];
	}
	else {
		[self.lyricsText setString:track.lyrics];
	}
	
	[track release];
}

- (void) updateLyrics:(NSNotification *)notification {
	NSString *lyrics = [[notification userInfo] objectForKey:@"Lyrics"];
	TrackInfo *targetTrack = [[notification userInfo] objectForKey:@"Track"];
	if ([lyrics length] != 0) {	
		//if (![controller isCurrentTrack:targetTrack])
		//	return;
		
		BOOL automaticUpdate = [self.updateLyricsIfEmptyItem state] == NSOnState && 
							   [targetTrack.lyrics length] == 0;
		
		if (automaticUpdate) {
			[self.controller updateCurrentTrackLyrics:lyrics];
		}
		
		[self.lyricsText setString:lyrics];
	}

}

- (void) dealloc {
	[self unsubscribeFromNotifications];
	[[NSStatusBar systemStatusBar] removeStatusItem:self.statusItem];
	
	self.statusItem = nil;
	self.controller = nil;
	self.provider = nil;
	
	[super dealloc];
}

@end
